package com.ete.service.net.exception

import android.net.ParseException
import com.google.gson.JsonParseException
import com.google.gson.stream.MalformedJsonException
import org.apache.http.conn.ConnectTimeoutException
import org.json.JSONException
import retrofit2.HttpException
import java.io.IOException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import javax.net.ssl.SSLException

/**
 * 将异常的英文信息转换成中文信息
 * Created by goldze on 2017/5/11.
 */
object ExceptionTranslate {

    private const val UNAUTHORIZED = 401
    private const val FORBIDDEN = 403
    private const val NOT_FOUND = 404
    private const val REQUEST_TIMEOUT = 408
    private const val INTERNAL_SERVER_ERROR = 500
    private const val SERVICE_UNAVAILABLE = 503

    @JvmStatic
    fun translateException(e: Throwable): HttpResponseException {
        val ex = HttpResponseException(e)
        return when (e) {
            // HTTP相关异常
            is HttpException -> {
                when (e.code()) {
                    UNAUTHORIZED -> ex.message = "操作未授权"
                    FORBIDDEN -> ex.message = "请求被拒绝"
                    NOT_FOUND -> ex.message = "资源或接口不存在"
                    REQUEST_TIMEOUT -> ex.message = "服务器执行超时"
                    INTERNAL_SERVER_ERROR -> ex.message = "服务器内部错误"
                    SERVICE_UNAVAILABLE -> ex.message = "服务器不可用"
                    else -> ex.message = "网络错误"
                }
                ex
            }
            is JsonParseException, is JSONException, is ParseException, is MalformedJsonException -> {
                ex.message = "数据解析错误"
                ex
            }
            is ConnectException -> {
                ex.message = "连接服务器失败, 请检查网络"
                ex
            }
            is SSLException -> {
                ex.message = "证书验证失败"
                ex
            }
            is ConnectTimeoutException -> {
                ex.message = "连接服务器超时"
                ex
            }
            is SocketTimeoutException -> {
                if (e.message != null && e.message!!.startsWith("failed to connect to")) {
                    ex.message = "连接服务器失败, 请检查网络"
                } else if (e.message != null && e.message!!.contains("timeout")) {
                    ex.message = "数据传输超时"
                } else {
                    ex.message = "连接服务器超时, 请检查网络"
                }
                ex
            }
            is UnknownHostException -> {
                ex.message = "解析服务器域名失败, 请检查网络"
                ex
            }
            is IOException -> {
                ex.message = "数据传输异常"
                ex
            }
            else -> {
                ex.message = e.message ?: "未知错误"
                ex
            }
        }
    }
}